<?php
/**
 * Created by KLXQ
 * user: youyi
 * Date：2024/6/28  下午2:12.
 * Tencent SDK.
 * 目前主要用于获取联合身份临时访问凭证.
 */

namespace App\Http\Helpers\Tencent;

use App\Services\TencentRequestService;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Sts\V20180813\StsClient;

class StsTencent
{
    public string $secretId;
    public string $secretKey;
    public string $region;
    public string $endpoint = 'sts.tencentcloudapi.com';
    public string $version = '2018-08-13';
    public object $client;
    public int $sdkAppId;
    public array $policy = [
        'version' => '3.0',
        'statement' => [
            [
                'action' => 'sts:*',
                'effect' => 'allow',
                'resource' => '*',
            ],
            [
                'action' => 'asr:*',
                'effect' => 'allow',
                'resource' => '*',
            ],
        ],
    ];

    public array $resultArr = ['code' => 200, 'msg' => 'success', 'data' => []];

    public function __construct($action, $params)
    {
        $this->secretId = config('tencent.tencent_cloud_secret_id');
        $this->secretKey = config('tencent.tencent_cloud_secret_key');
        $this->region = config('tencent.trtc.region');
        $this->sdkAppId = (int) config('tencent.trtc.app_id');

        try {
            $cred = new Credential($this->secretId, $this->secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint($this->endpoint);

            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            $this->client = new StsClient($cred, $this->region, $clientProfile);

            $params['Policy'] = urlencode(json_encode($this->policy, JSON_UNESCAPED_UNICODE));
            $params['DurationSeconds'] = 7200;

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $respClass = 'TencentCloud\\'.ucfirst('sts').'\\V20180813\\Models\\'.ucfirst($action).'Request';
            $req = new $respClass();
            $req->fromJsonString(json_encode($params));
            // 返回的resp是一个RemoveUserResponse的实例，与请求对象对应
            $resp = $this->client->{$action}($req);

            $this->resultArr['data'] = json_decode($resp->toJsonString(), true);
        } catch (TencentCloudSDKException $e) {
            $this->resultArr['code'] = -1;
            $this->resultArr['msg'] = $e->getMessage();
        }

        // 记录日志
        TencentRequestService::create('sts', $action, $params, $this->resultArr);
    }
}
